package com.yaowk.sfp.file.local;

import com.yaowk.sfp.file.api.BaseFileUtils;
import com.yaowk.sfp.file.api.exception.FileException;
import com.yaowk.sfp.file.api.model.FileModel;
import com.yaowk.sfp.file.server.service.IFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 将文件存入数据库
 *
 * @author 小凯
 **/
@Service
@Slf4j
public class LocalFileUtils extends BaseFileUtils {

    @Value("${yaowk.file.local.path}")
    private String path;
    @Value("${yaowk.file.local.urlPrefix}")
    private String urlPrefix;

    private static final DateFormat FORMAT = new SimpleDateFormat("/yyyy/MM/dd/");

    @Autowired
    private IFileService fileService;

    @Override
    public FileModel upload(MultipartFile file) {
        FileModel fileModel = buildFileModel(file);

        FileModel param = new FileModel();
        param.setMd5(fileModel.getMd5());
        param.setSize(fileModel.getSize());

        List<FileModel> all = fileService.findAll(param);
        if (CollectionUtils.isNotEmpty(all)) {
            fileModel = all.get(0);
        } else {
            String dir = FORMAT.format(new Date());
            String fileName = fileModel.getMd5() + fileModel.getSize() + getExtension(fileModel.getName());
            try {
                File ff = new File(path + dir);
                if (!ff.exists()) {
                    ff.mkdirs();
                }
                file.transferTo(new File(path + dir + fileName));
            } catch (IOException e) {
                e.printStackTrace();
                throw new FileException("文件保存错误");
            }
            fileModel.setFile(urlPrefix + dir + fileName);
            fileModel = fileService.save(fileModel);
        }
        return fileModel;
    }
}
